package com.purdue.edu.psychotron.client.entity;

import javax.persistence.Id;

import com.googlecode.objectify.annotation.Entity;
import com.purdue.edu.psychotron.client.entity.MessageBuffer.Builder;
import com.purdue.edu.psychotron.shared.UUID;


@SuppressWarnings("serial")
@Entity
public class MessageBuffer {
	@Id
	String messageBufferId;
	String userAId;
	String userBId;
	String contentFromAtoB;
	String contentFromBtoA;
	Boolean consecutiveFromAtoB;
	Boolean consecutiveFromBtoA;
	
	public MessageBuffer() {
	}

	public static class Builder {
		private MessageBuffer MessageBuffer = new MessageBuffer();

		public Builder(MessageBuffer MessageBuffer) {
			this.MessageBuffer = MessageBuffer;
		}

		public Builder(String userAId, String userBId) {
			this.MessageBuffer = new MessageBuffer();
			this.MessageBuffer.userAId = userAId;
			this.MessageBuffer.userBId = userBId;
			if(userAId.compareTo(userBId) < 0)
				this.MessageBuffer.messageBufferId = userAId+userBId;
			else
				this.MessageBuffer.messageBufferId = userBId+userAId;
			this.MessageBuffer.contentFromAtoB = "";
			this.MessageBuffer.contentFromBtoA = "";
			this.MessageBuffer.consecutiveFromAtoB = false;
			this.MessageBuffer.consecutiveFromBtoA = false;
		}


		public Builder addMessage(String senderId, String newMessage) {
			if(senderId.equals(this.MessageBuffer.userAId)){
				if(this.MessageBuffer.consecutiveFromAtoB){
					newMessage = "\r\n"+newMessage;
				}else{
					this.MessageBuffer.consecutiveFromAtoB = true;
				}
				this.MessageBuffer.contentFromAtoB += newMessage;
			}
			else if (senderId.equals(this.MessageBuffer.userBId)){
				if(this.MessageBuffer.consecutiveFromBtoA){
					newMessage = "\r\n"+newMessage;
				}else{
					this.MessageBuffer.consecutiveFromBtoA = true;
				}
				this.MessageBuffer.contentFromBtoA += newMessage;
			}
			return this;
		}

		public Builder flushByRequesterId(String userId){
			if(userId.equals(this.MessageBuffer.userAId)){
				this.MessageBuffer.contentFromBtoA = "";
				this.MessageBuffer.consecutiveFromBtoA = false;
			}
			else if (userId.equals(this.MessageBuffer.userBId)){
				this.MessageBuffer.contentFromAtoB = "";
				this.MessageBuffer.consecutiveFromAtoB = false;
			}
			return this;
		}

		public MessageBuffer build() {
			return this.MessageBuffer;
		}
	}

	public boolean checkIfBothMatch(String user1Id, String user2Id){
		if((user1Id.equals(userAId) || user1Id.equals(userBId)) && (user2Id.equals(userAId) || user2Id.equals(userBId)) ){
			return true;
		}
		return false;
	}

	public String getUserAId() {
		return userAId;
	}

	public String getUserBId() {
		return userBId;
	}

	public String getMessageBufferId() {
		return messageBufferId;
	}

	public String getContentByRequesterId(String requesterId) {
		if(requesterId.equals(userAId)){
			return contentFromBtoA;
		}
		else{
			return contentFromAtoB;
		}
	}

}